package com.finger.forest;

import android.content.Intent;
import android.graphics.Color;
import android.graphics.drawable.BitmapDrawable;
import android.os.Bundle;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.MotionEvent;
import android.view.View;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.LinearLayout;

import androidx.appcompat.app.AppCompatActivity;
import androidx.core.content.ContextCompat;

import com.esri.arcgisruntime.ArcGISRuntimeEnvironment;
import com.esri.arcgisruntime.concurrent.ListenableFuture;
import com.esri.arcgisruntime.data.Feature;
import com.esri.arcgisruntime.data.FeatureCollection;
import com.esri.arcgisruntime.data.FeatureCollectionTable;
import com.esri.arcgisruntime.data.Field;
import com.esri.arcgisruntime.geometry.Envelope;
import com.esri.arcgisruntime.geometry.GeometryType;
import com.esri.arcgisruntime.geometry.Point;
import com.esri.arcgisruntime.geometry.SpatialReferences;
import com.esri.arcgisruntime.layers.FeatureCollectionLayer;
import com.esri.arcgisruntime.location.LocationDataSource;
import com.esri.arcgisruntime.mapping.ArcGISMap;
import com.esri.arcgisruntime.mapping.Basemap;
import com.esri.arcgisruntime.mapping.GeoElement;
import com.esri.arcgisruntime.mapping.view.Callout;
import com.esri.arcgisruntime.mapping.view.DefaultMapViewOnTouchListener;
import com.esri.arcgisruntime.mapping.view.Graphic;
import com.esri.arcgisruntime.mapping.view.GraphicsOverlay;
import com.esri.arcgisruntime.mapping.view.IdentifyGraphicsOverlayResult;
import com.esri.arcgisruntime.mapping.view.LocationDisplay;
import com.esri.arcgisruntime.mapping.view.MapView;
import com.esri.arcgisruntime.symbology.PictureMarkerSymbol;
import com.esri.arcgisruntime.symbology.SimpleRenderer;
import com.esri.arcgisruntime.symbology.TextSymbol;
import com.finger.forest.base.CommonKey;
import com.finger.forest.base.SystemConfig;
import com.finger.forest.custom.MyDialog;
import com.finger.forest.utils.ClickUtils;
import com.finger.forest.utils.ToastUtils;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.concurrent.ExecutionException;

import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;

/**
 * 去地图定位
 */
public class ToMapLocationActivity extends AppCompatActivity implements View.OnClickListener {

    private static final String TAG = "ToMapLocationActivity";

    /**
     * 返回
     */
    @BindView(R.id.btn_back)
    ImageView backIv;

    private MapView mMapView;

    //经度（界面传值）
    private String longitude;

    //纬度（界面传值）
    private String latitude;

    //热点ID（界面传值）
    private String hId;

    //热点编号（界面传值）
    private String hHotspotNo;

    private MyDialog myDialog;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_to_map_location);
        ButterKnife.bind(this);

        //接收热点经纬度
        Intent intent=getIntent();
        longitude = intent.getStringExtra("longitude");
        latitude = intent.getStringExtra("latitude");
        hId = intent.getStringExtra("hId");
        hHotspotNo = intent.getStringExtra("hHotspotNo");

        mMapView = findViewById(R.id.mapView);
        setupMap();

        //添加热点和巡护员位置
        createFeatureCollection();

        //添加热点图标
        createPointGraphics();

    }

    /**
     * 添加热点图标
     */
    private void createPointGraphics() {
        GraphicsOverlay mGraphicsOverlay = new GraphicsOverlay();
        mMapView.getGraphicsOverlays().add(mGraphicsOverlay);

        Point point2 = new Point(Double.parseDouble(longitude), Double.parseDouble(latitude), SpatialReferences.getWgs84());
        BitmapDrawable bitmapDrawable = (BitmapDrawable) ContextCompat.getDrawable(this, R.drawable.ic_fire);
        PictureMarkerSymbol pms = new PictureMarkerSymbol(bitmapDrawable);
        Graphic pointGraphic2 = new Graphic(point2, pms);
        mGraphicsOverlay.getGraphics().add(pointGraphic2);
    }

    private void setupMap() {
        if (mMapView != null) {
            ArcGISRuntimeEnvironment.setLicense(CommonKey.LICENSE);
            mMapView.setAttributionTextVisible(false);
            Basemap.Type basemapType = Basemap.Type.IMAGERY;
            ArcGISMap map = new ArcGISMap(basemapType, Double.parseDouble(latitude), Double.parseDouble(longitude), SystemConfig.mapLevel);
            mMapView.setMap(map);
        }

        mMapView.setOnTouchListener(new DefaultMapViewOnTouchListener(ToMapLocationActivity.this, mMapView) {
            @Override
            public boolean onSingleTapUp(MotionEvent e) {
                Log.i(TAG,e.getX()+","+e.getY());
                Log.i(TAG,"点击");
                //获取屏幕点击坐标
                android.graphics.Point mapPoint =  new android.graphics.Point((int)e.getX(),(int)e.getY());
                //将屏幕坐标 传入 identifyGraphicsOverlaysAsync （屏幕坐标，范围，包括图形和弹出窗口时为false，最大检索数）
                final ListenableFuture<List<IdentifyGraphicsOverlayResult>> listListenableFuture = this.mMapView.identifyGraphicsOverlaysAsync(mapPoint,12, false, 5);
                //this.mMapView.identifyLayerAsync(mMapView.getMap().getOperationalLayers(),mapPoint,12, false, 5);
                //添加点击事件
                listListenableFuture.addDoneListener(new Runnable() {
                    @Override
                    public void run() {
                        try {
                            //获取点击的范围列表
                            List<IdentifyGraphicsOverlayResult> identifyLayerResults = listListenableFuture.get();
                            //循环图层
                            for (IdentifyGraphicsOverlayResult identifyLayerResult : identifyLayerResults) {
                                //循环所点击要素
                                for (final GeoElement geoElement : identifyLayerResult.getGraphics()) {
                                    Envelope tEnvelope = geoElement.getGeometry().getExtent();
                                    Point tPoint = tEnvelope.getCenter();
                                    Log.e(TAG,"当前点击的："+tPoint);

                                    LinearLayout layoutHotContent = (LinearLayout)LayoutInflater.from(ToMapLocationActivity.this).inflate(R.layout.dialog_content_hot, null);

                                    //弹框
                                    myDialog=new MyDialog(ToMapLocationActivity.this,R.style.MyDialog);
                                    myDialog.setTitle("热点信息");
                                    myDialog.setLayout(layoutHotContent);
                                    myDialog.setYesOnclickListener("去反馈", new MyDialog.onYesOnclickListener() {
                                        @Override
                                        public void onYesOnclick() {
                                            ToastUtils.show("去反馈");
                                        }
                                    });
                                    myDialog.setNoOnclickListener("取消", new MyDialog.onNoOnclickListener() {
                                        @Override
                                        public void onNoClick() {
                                            myDialog.dismiss();
                                        }
                                    });
                                    myDialog.show();


                                }
                            }
                        } catch (InterruptedException e) {
                            e.printStackTrace();
                        } catch (ExecutionException e) {
                            e.printStackTrace();
                        }
                    }
                });
                return super.onSingleTapUp(e);
            }
        });
    }

    //创建要素集合
    FeatureCollection featureCollection = new FeatureCollection();
    //创建要素集合图层
    FeatureCollectionLayer featureCollectionLayer = new FeatureCollectionLayer(featureCollection);

    //添加热点和巡护员位置
    private void createFeatureCollection() {
        //将图层添加到地图
        mMapView.getMap().getOperationalLayers().add(featureCollectionLayer);
        createPointTable(featureCollection);
    }

    //自定义图标
    private SimpleRenderer getDrawableIcon(int draIcon){
        BitmapDrawable bitmapDrawable = (BitmapDrawable) ContextCompat.getDrawable(this, draIcon);
        PictureMarkerSymbol pms = new PictureMarkerSymbol(bitmapDrawable);
        SimpleRenderer renderer = new SimpleRenderer(pms);
        return renderer;
    }

    /**
     * 添加热点名称
     * @param featureCollection
     */
    private void createPointTable(FeatureCollection featureCollection) {

        List<Field> pointFields = new ArrayList<>();
        pointFields.add(Field.createString("Place", "Place Name", 50));

        //------ 文字 start--------
        //要素集合table
        FeatureCollectionTable pointsTableT = new FeatureCollectionTable(pointFields, GeometryType.POINT, SpatialReferences.getWgs84());
        TextSymbol textSymbol = new TextSymbol(10, "热点", Color.WHITE, TextSymbol.HorizontalAlignment.CENTER, TextSymbol.VerticalAlignment.TOP);
        textSymbol.setOffsetY(-10);
        textSymbol.setFontFamily("DroidSansFallback.ttf");
        SimpleRenderer renderer = new SimpleRenderer(textSymbol);
        pointsTableT.setRenderer(renderer);

        // Malibu Pier
        Map<String, Object> attributesT = new HashMap<>();
        attributesT.put(pointFields.get(0).getName(), "Malibu Pier");
        Point pointT = new Point(Double.parseDouble(longitude), Double.parseDouble(latitude), SpatialReferences.getWgs84());

        List<Feature> featuresT = new ArrayList<>();
        featuresT.add(pointsTableT.createFeature(attributesT, pointT));

        pointsTableT.addFeaturesAsync(featuresT);

        //热点
        featureCollection.getTables().add(pointsTableT);
        //------ 文字 end--------

    }

    @OnClick({R.id.btn_back })
    @Override
    public void onClick(View v) {
        if (ClickUtils.isFastClick()) { //防止重复点击
            switch (v.getId()) {

                //返回
                case R.id.btn_back:
                    finish();
                    break;

                default:
                    break;
            }
        }
    }

    @Override
    public void onPause() {
        super.onPause();
        // pause MapView
        mMapView.pause();
    }

    @Override
    public void onResume() {
        super.onResume();
        // resume MapView
        mMapView.resume();
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        // dispose MapView
        mMapView.dispose();
    }

}
